﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace DCT.CodeBox.EventTrigger.Codes
{
    /// <summary>
    /// 事件触发器公开属性
    /// </summary>
    /// <typeparam name="TArgument"></typeparam>
    public class EventTriggerListener<TArgument>
    {
        private List<Func<TArgument, bool>> listeners;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="listeners"></param>
        public EventTriggerListener(List<Func<TArgument, bool>> listeners)
        {
            this.listeners = listeners;
        }

        /// <summary>
        /// 添加监听
        /// </summary>
        /// <param name="listener"></param>
        public void Add(Func<TArgument, bool> listener)
        {
            lock (this.listeners)
            {
                this.listeners.Add(listener);
            }
        }

        /// <summary>
        /// 移除监听
        /// </summary>
        /// <param name="listener"></param>
        /// <returns></returns>
        public bool Remove(Func<TArgument, bool> listener)
        {
            lock (this.listeners)
            {
                return this.listeners.Remove(listener);
            }
        }

        /// <summary>
        /// 移除监听
        /// </summary>
        /// <param name="index">索引</param>
        /// <returns>是否移除，如果索引不正确会返回false</returns>
        public bool RemoveAt(int index) {
            bool succ = false;
            if (index >= 0 && this.listeners.Count > index)
            {
                lock (this.listeners)
                {
                    this.listeners.RemoveAt(index);
                }
                succ = true;
            }
            return succ;
        }

        /// <summary>
        /// 清空所有监听
        /// </summary>
        public void Clear()
        {
            lock (this.listeners)
            {
                this.listeners.Clear();
            }
        }

        /// <summary>
        /// 查看监听器所在索引位置
        /// </summary>
        /// <param name="listener"></param>
        /// <returns></returns>
        public int GetIndex(Func<TArgument, bool> listener)
        {
            return this.listeners.IndexOf(listener);
        }

        /// <summary>
        /// 查看所有监听器
        /// </summary>
        public ReadOnlyCollection<Func<TArgument, bool>> Listeners
        {
            get
            {
                return this.listeners.AsReadOnly();
            }
        }

    }
}
